<?php

class HomeAction extends Action {
	//保养数据
	public function saveOrder(){
		$UA=M("user_auto");
		$AM=M("auto_model");
		//获取车型数据
		$dataAuto['model_id']=$_SESSION['order']['model_id'];
		$dataAuto['create_time']=time();
		$auto=$AM->where("model_id=".$_SESSION['order']['model_id'])->find();
		//查看是否已注册
		$U = M("user");
		$data['username'] = $_SESSION['order']['phone'];
		$userInfo=$U->where($data)->field("user_id,open_id,username,nickname,realname,address")->find();
		$ua_id = 0;
	
		import("@.ORG.MobileSms");
		$mobilesms = new MobileSms();
	
		$_SESSION['user']=$userInfo;
		if (!$userInfo||empty($_SESSION['user'])) {
			//注册用户并插入数据
			$userInfo['create_time'] = time();
			$userInfo['tel'] = $_POST['phone'];
			$userInfo['nickname'] = $_POST['phone'];
			$userInfo['username'] = $_POST['phone'];
			$userInfo['password'] = md5("123456");
			$userInfo['realname']=$_POST['realname'];
			$userInfo['address']=$_POST['address'];
			if($_SESSION['open_id']){
				$userInfo['open_id'] = $_SESSION['open_id'];
			}
			$user_id = $U->add($userInfo); //注册用户
			if($user_id){
				$userInfo['user_id'] = $user_id;
				$_SESSION['user'] = $userInfo;              //session记录数据
				$dataAuto['user_id']=$user_id;
				$dataAuto['default']=1;
				if($_SESSION['order']['source']==3){
					$content='尊敬的用户：您的氦修帐号已生成，用户名为:'.$data['username'].'，初始密码为：123456，为了您的帐号安全，请尽快修改您的密码！如有疑问请致电客服热线400-673-0088。';
					$rs = $mobilesms->send($userInfo['username'], $content);
				}
				$ua_id = $UA->add($dataAuto);  //添加车型
			}
		}else{
			if(!empty($_SESSION['open_id'])){
				//绑定微信OPENID
				$dataUserInfo['open_id']=$_SESSION['open_id'];
			}
			$dataUserInfo['realname']=$_SESSION['order']['realname'];
			if(!empty($_SESSION['order']['address'])){
				$dataUserInfo['address']=$_SESSION['order']['address'];
			}
			$res = $U->where("user_id=".$userInfo['user_id'])->save($dataUserInfo);

			$dataAuto['user_id']=$userInfo['user_id'];
			$user_id=$userInfo['user_id'];
			//存在该用户，判断是否插入车型数据
			$hasAuto=$UA->where("model_id=".$_SESSION['order']['model_id']." and user_id=".$userInfo['user_id'])->find();
			
			if($hasAuto==null||$hasAuto===false){
				$ua_id = $UA->add($dataAuto);
			}else{
				$ua_id = $hasAuto['ua_id'];
			}
			$_SESSION['user'] = $userInfo;              //session记录数据
		}
	
		$dataPJ=$this->getJYJV($auto['capacity']);
	
		$PjTotal=0;
		foreach($dataPJ as $key =>$value){
			$count=empty($value['count'])?1:$value['count'];
			$PjTotal+=$value['pj_csprice']*$count;
		}

		$isOfficeShop=in_array($_SESSION['order']['wx_id'],C("officeShop"));	//是否线下店安装


		$PjTotal=$isOfficeShop?$PjTotal+150:$PjTotal;
		$Total=$PjTotal;
		$dataOrder['order_num']=time().rand(100, 999);
		$dataOrder['user_id']=$_SESSION['user']['user_id'];
		$dataOrder['wx_id']=empty($_SESSION['order']['wx_id'])?0:$_SESSION['order']['wx_id'];
		$dataOrder['total_price'] = $PjTotal;
		$dataOrder['all_price'] = $Total;
		$dataOrder['ua_id']=$ua_id;
		$dataOrder['model_id']=$_SESSION['order']['model_id'];
		$dataOrder['create_time']=time();
		$dataOrder['service_price']=$isOfficeShop?150:0;

		$dataOrder['type']=$isOfficeShop?1:2;

		$dataOrder['yy_date']=$_POST['yy_date'];
		$dataOrder['yy_time']=$_POST['yy_time'];
		$dataOrder['uo_type']=3;
		$dataOrder['status']=5;
		$dataOrder['source']=$_SESSION['order']['source'];
		$dataOrder['order_name']="小保养";
		$partOrder=M('order');
		$order_id=$partOrder->add($dataOrder);
		$_SESSION['order']['order_id']=$order_id;
	
		if($order_id!==false){
			$PJ=M("peijian");
			foreach($dataPJ as $key=>$value){
				$dataInfo[$key]['order_id']=$order_id;
				$dataInfo[$key]['pj_id']=$value['pj_id'];
				$dataInfo[$key]['pj_name']=$value['pj_name'];
				$dataInfo[$key]['logo']=$value['logo'];
				$dataInfo[$key]['user_id']=$user_id;
				$dataInfo[$key]['count']=$value['count'];
				$dataInfo[$key]['pj_cbprice']=$value['pj_cbprice'];
				$dataInfo[$key]['pj_scprice']=$value['pj_scprice'];
				$dataInfo[$key]['pj_csprice']=$value['pj_csprice'];
				$dataInfo[$key]['total']=$value['pj_csprice']*$value['count'];
				$dataInfo[$key]['status']=1;
			}
			$orderInfo=M("order_info");
			$orderInfo->addAll($dataInfo);
	
			//处理优惠券
			$code=$_POST['coupon'];
			$couponId = 0;
			if($code){
				$coupon = M('coupon_user')->join("left join hx_coupon as c ON c.c_id=hx_coupon_user.c_id")->where("code=$code and status=1")->find();
				$couponId = $coupon['cu_id'];
				if($coupon['type'] == 1 && $Total>$coupon['low_money']){              //满减(定额)
					if($Total <= $coupon['money']){
						$PjTotal = 0.01;
						$Total = 0.01;
					}else{
						$PjTotal = $PjTotal-$coupon['money'];
						$Total = $Total-$coupon['money'];
					}
				}elseif($coupon['type'] == 2 && $Total>$coupon['low_money']){         //满减(百分比)
					$money = $Total*$coupon['money'];
					if($money > $coupon['high_money']){
						$PjTotal = $PjTotal-$coupon['high_money'];
						$Total = $Total-$coupon['high_money'];
					}else{
						$PjTotal = $PjTotal-$money;
						$Total = $Total-$money;
					}
				}elseif($coupon['type'] == 4){
					$jiyouMoney = 0;
					$otherMoney = 0;
					for ($i=0;$i<count($dataInfo);$i++){
						if($i==0 || $i==2){
							$jiyouMoney += $dataInfo[$i]['total'];
						}else{
							$otherMoney += $dataInfo[$i]['total'];
						}
					}
					if($jiyouMoney>=200){               //机油价格大于 200
						$PjTotal = $coupon['rand_money'] - (200 + $otherMoney);
						if(!$PjTotal){
							$PjTotal = 0.01;
							$Total = 0.01;
						}
					}else{                              //机油价格小于 200
						$PjTotal = $coupon['rand_money'] - ($jiyouMoney + $otherMoney);
						if(!$PjTotal){
							$PjTotal = 0.01;
							$Total = 0.01;
						}
					}
				}
	
				if($couponId){              //优惠券已使用
					$datacoupon=array();
					$datacoupon['cu_id'] = $couponId;
					$datacoupon['status'] = 0;
					M('coupon_user')->save($datacoupon);
	
					$datamoney=array();     //更新订单金额
					$datamoney['order_id'] = $order_id;
					$datamoney['total_price'] = $PjTotal;
					$datamoney['all_price'] = $Total;
					$datamoney['cu_id'] = $couponId;
					$partOrder->save($datamoney);
				}
			}
			 
/* 			$dataLog['order_id']=$order_id;
			$dataLog['action']="XD";
			$dataLog['name']='下单时间';
			$dataLog['time']=$dataOrder['create_time'];
			M("orderlog")->add($dataLog);
	 */
			if($_SESSION['order']['source']==4&&!empty($_SESSION['open_id'])&&!$isOfficeShop){
				echo $this->pay($order_id);
			}elseif($_SESSION['order']['source']==3){
				return $order_id;
			}else{
				unset($_SESSION['order']['wx_id']);
				echo $order_id;
			}
		}else{
			log::write("用户".$_SESSION['user']['username']."下单失败");
		}
	}
	
	//计算机油机滤数据
	public function getJYJV($jyVal){
		$PJ=M("peijian");
		$map['pj_id']=array("in",$_SESSION['order']['goodsId']);
		$peijian=$PJ->where($map)->select();
	
		if($peijian[0]['type_id']==1){
			$data[]=$peijian[0];    //4升机油数据
			$data[]=$peijian[1];    //机滤数据
		}else{
			$data[]=$peijian[1];
			$data[]=$peijian[0];
		}
		
		//重置机滤价格
		$data[1]['pj_name']=$data[1]['pj_pinpai'];
		$data[1]['count']=1;

		$data[0]['count']=floor($jyVal/4);

		if($data[0]['pj_id']==287||$data[0]['pj_id']==293){
			$data[0]['count']=$jyVal;
		}elseif($jyVal%4!=0){
			$mapOne['pj_id']=C("JIYOU")[$data[0]['pj_id']];
			$data[2]=$PJ->where($mapOne)->find();
			$data[2]['count']=$jyVal%4;
		}
		//如果选购了周边产品-移动端
		if(!empty($_SESSION['order']['otherPJ'])){
			$len=count($data);
			$mapOther['pj_id']=array("in",$_SESSION['order']['otherPJ']);
			$otherPJ=$PJ->where($mapOther)->select();
			$data=array_merge($data,$otherPJ);
		}

		return $data;
	}
	
	//确认收货
	public function receive(){
		if(empty($_POST['order_id'])){
			$this->ajaxReturn(null, "缺少参数", -1001);
		}
		$order_id=$_POST['order_id'];
		$Info = M('order')->where("order_id=$order_id")->find();
		if($Info["status"]==30){
			$data['order_id'] = $order_id;
			$data['status'] = 40;
			$res = M('order')->save($data);
			if($res){
				$this->ajaxReturn(null, "收货成功", 1);
			}else{
				$this->ajaxReturn(null, "操作失败", -1002);
			}
		}else{
			$this->ajaxReturn(null, "当前订单不可收货或操作失败", -1003);
		}
	}
	
	//用户评价维修厂
	public function commentInset() {
		if (empty($_REQUEST['order_id']) || empty($_REQUEST['pingfen'])) {
			$this->ajaxReturn(null, "缺少参数", -1001);
		}
	
		$order_id = $_REQUEST['order_id'];
		$wheres['order_id'] = $order_id;
		$comment = M('comment')->field('id')->where($wheres)->find();
		if($comment){
			$this->ajaxReturn(null, "您已评论过", -1003);
		}
		$order = M('order')->field('wx_id,status')->where($wheres)->find();
/* 		if($order['status']!=60){
			$this->ajaxReturn(null, "当前订单不可评论", -1004);
		} */
		
		$data['gdtx'] = $_REQUEST['pingfen'];
		$data['dnhj'] = $_REQUEST['pingfen'];
		$data['fwtd'] = $_REQUEST['pingfen'];
		$data['wxsd'] = $_REQUEST['pingfen'];
		$data['wxzl'] = $_REQUEST['pingfen'];
		$data['qita'] = $_REQUEST['pingfen'];
		$data['commentTxt'] = $_REQUEST['content'];
		$data['order_id'] = $_REQUEST['order_id'];
		$data['wx_id'] = $order['wx_id'];
		$data['user_id'] = $_SESSION['user']['user_id'];
		$data['status'] = '1';
		$data['create_time'] = time();
		 
		$total = $data['gdtx']+$data['dnhj']+$data['fwtd']+$data['wxsd']+$data['wxzl']+$data['qita'];
		$data['average'] = sprintf("%.1f", $total/6);
		$res = M("comment")->add($data);
		 
		$where = array();
		$where['id'] = $data['wx_id'];
		$company = M('company')->field('onestar,twostar,threestar,fourstar,fivestar,comment_count,comment_score')->where($where)->find();
		 
		$count = $company['comment_count']+1;
		$score = $company['comment_score']+$data['average'];
		 
		$comment = array();
		$comment['id'] = $data['wx_id'];
		$comment['average'] = sprintf("%.1f", $score/$count);
		$comment['comment_count'] = $count;
		$comment['comment_score'] = $score;
		$star = floor($data['average']);
		if($star == 1){
			$comment['onestar'] = $company['onestar']+1;
		}elseif($star == 2){
			$comment['twostar'] = $company['twostar']+1;
		}elseif($star == 3){
			$comment['threestar'] = $company['threestar']+1;
		}elseif($star == 4){
			$comment['fourstar'] = $company['fourstar']+1;
		}elseif($star == 5){
			$comment['fivestar'] = $company['fivestar']+1;
		}
		 
		$cres = M('company')->save($comment);
		if($res){
			$order = array();
			$order['is_comment'] = '1';  //评论后状态
			$order['order_id'] = $order_id;
			$orderRes = M('order')->save($order);
	
			$this->ajaxReturn($res, "评价成功", 1);
		}else{
			$this->ajaxReturn(null, "评价失败", -1002);
		}
	}
	
	//获取车型数据
	public function getAuto(){
		if(!empty($_POST)){
			$AMC = M('auto_model');
			$map = $_POST;

			if(!empty($_POST['model_pl'])){
				$order="model_year desc";
			}else if(!empty($_POST['model_name'])){
				$order="model_pl desc";
			}

			$car = $AMC->where($map)->field("model_id,brand_id,brand_name,model_name,model_pl,model_year,brand_logo")->order($order)->select();
			if($car!==false){
				$this->ajaxReturn($car, "查询成功", 1);
			}else{
				$this->ajaxReturn($car, "查询失败", 0);
			}
		}else{
			$U = M('auto');
			$map['parentId'] = 0;
			$map['brand_id']=array("in",$_SESSION['pjs']['p_brand_id']);
			
			$car = $U->where($map)->field("brand_id,brand_name,brand_logo,letter")->select();
			if($car!==false){
				$this->ajaxReturn($car, "查询成功", 1);
			}else{
				$this->ajaxReturn($car, "查询失败", 0);
			}
		}
	}
	
	//登陆
	public function login() {
		if (empty($_POST['username']) || empty($_POST['password'])) {
			$this->ajaxReturn(null, "缺少参数", -1001);
		}
	
		$map['username'] = $_POST['username'];
		$U = M('user');
		$res = $U->where($map)->field("user_id,username,password,nickname,headImage,realname,sex,zone,address,tel,email,driving,desc,create_time,loginTime,deviceToken,goCompany")->find();
		if($res['username']=='') {
			$this->ajaxReturn(null, "该帐号不存在", 1001);
		}
	
		if ($res){
			if ($res['password'] != md5($_POST['password'])) {
				$this->ajaxReturn(null, "密码错误", 1500);
			}
	
			//用户拥有的车型
			$res['userAuto'] = $this->userAllAuto($res['user_id']);
			$res['token']= md5(time());
			$_SESSION['user'] = $res;
			 
			$data['loginTime']=$res['loginTime']+1;
			$data['lastLoginTime']=time();
			$data['token']= $res['token'];
			$data['user_id']=$res['user_id'];
			$U->save($data);
	
			$this->ajaxReturn($res, "登录成功", 1);
		}else{
			$this->ajaxReturn(null, "未知错误", 0);
		}
	}
	
	public function reg() {
		if (!preg_match("/^(13|15|18|14|17)[0-9]{9}$/", $_POST['username'])) {
			$this->ajaxReturn(null, "请输入正确的手机号", -1);
		}
		if (empty($_POST['code'])) {
			$this->ajaxReturn(null, "请输入正确的验证码", -2);
		}
		if ($_POST['pwd'] != $_POST['conPwd']) {
			$this->ajaxReturn(null, "二次输入密码不一致", -5);
		}
	
		$U = M("user");
		$data['username'] = $_POST['username'];
		$res = $U->where($data)->getField("user_id");
		if ($res) {
			$this->ajaxReturn(null, "该手机已注册，请登录。", -3);
		}
	
		$S = M("sms");
		$mapSms['desc'] = $_POST['code'];
		$mapSms['to_phone'] = $_POST['username'];
		$mapSms['isused'] = 0;
	
		$code = $S->field("create_time")->where($mapSms)->order("create_time desc")->limit(1)->select();
	
		if ($code == false) {
			$this->ajaxReturn(null, "验证码错误", -6);
		}
		$code = $code[0]['create_time'];
		$S->where($mapSms)->setField("isused",1);
		if (($code + 5 * 60) < time()) {
			$this->ajaxReturn(null, "验证码已过期，请重新获取", -8);
		}
	
		$data['create_time'] = time();
		$data['tel'] = $data['username'];
		$data['nickname'] = $data['username'];
		$data['password'] = md5($_POST['password']);
		$data['source']=$_POST['source'];
		$res = $U->add($data);
		$_POST['phone']=$_POST['username'];
	
		if ($res) {
			$res = $U->where("user_id=" . $res)->find();
			unset($res['password']);
			$_SESSION['user'] = $res;
			$this->ajaxReturn($res, "注册成功", 1);
		} else {
			log::write("注册失败:" . $U->getLastSql());
			$this->ajaxReturn(null, "注册失败", 0);
		}
	}
	
	//注册全局验证
	public function regVal() {
		$U = M("user");
		$data['username'] = $_POST['username'];
		$res = $U->where($data)->getField("user_id");
		if ($res) {
			$this->ajaxReturn(null, "该手机已注册，请登录。", -3);
		}
	
		$S = M("sms");
		if (empty($_POST['pwd'])) {   //获取验证码
			$randStr = str_shuffle('1234567890');
			$rand = substr($randStr, 0, 6);
			import("@.ORG.MobileSms");
			$mobilesms = new MobileSms();
			$sms['to_phone'] = $_POST['username'];
			$sms['content'] = "您的验证码是：" . $rand . "。请在5分钟内使用，过期无效！";
	
			$rs = $mobilesms->send($sms['to_phone'], $sms['content']);
			if ($rs !== false) {
				$sms['type'] = 1;
				$sms['create_time'] = time();
				$sms['isused'] = 0;
				$sms['desc'] = $rand;
				$sms["out_id"] = $rs;
	
				$res = $S->add($sms);
				if ($res) {
					$this->ajaxReturn($rand, "验证码发送成功", 1);
				} else {
					$this->ajaxReturn(null, "发送验证码失败，请重试", -7);
				}
			}
		}
	}
	
	public function logout(){
		unset($_SESSION['user']);
		redirect(U('Index/index'));
	}

	//发送短信
	public function postSms($phone,$content){
		import("@.ORG.MobileSms");
        $mobilesms = new MobileSms();
        $rs = $mobilesms->send($phone, $content);
	}

	//获取微信JS-SDK使用权限算法
	public function getJsapiTicket($timestamp,$nonceStr){
		$tokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".C('weixinAppId')."&secret=".C("weixinKey");
		$token=file_get_contents($tokenUrl);
		$token=json_decode($token,true);
        $token=$token['access_token'];


        $ticketUrl="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$token."&type=jsapi";
        $ticket=file_get_contents($ticketUrl);
        $ticket=json_decode($ticket,true);
        $ticket=$ticket['ticket'];

        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		//$url="http://wap.99qby.com/mobile/myOrderInfoQBY.html?id=127";
        $string = "jsapi_ticket=$ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    	$signature = sha1($string);

		return $signature;
	}
	
	public function https_request($url,$data = null){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 40);
		curl_setopt($ch, CURLOPT_TIMEOUT, 40);
		if (!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data); }
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl); curl_close($curl);
		return $output;
	}
}

?>